package com.xxh.basecrudframework.config;

import com.xxh.basecrudframework.common.Result;
import com.xxh.basecrudframework.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * 异常捕获，统一格式返回
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理统一异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        log.error("Exception:", e);
        return Result.error();
    }

    /**
     * 校验异常处理
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
//        log.error("MethodArgumentNotValidException:", e);
        String msg = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(ResultCode.BODY_NOT_MATCH.getCode(),msg);
    }

    /**
     * 捕获断言校验异常
     */
    @ExceptionHandler({IllegalArgumentException.class})
    public Result illegalArgumentException(Exception e) {
        log.error("触发异常拦截: " + e.getMessage(), e);
        return Result.error(ResultCode.BODY_NOT_MATCH.getCode(),e.getMessage());
    }
}
